import {ref,reactive,toRaw } from 'vue'
import type { FormInstance, FormRules,UploadFile } from 'element-plus'
import { ElMessage } from "element-plus";
import { addUser,yztGetUserDetail } from '@/utils/api'
import { base64ToFile } from '@/utils/func';
import { type CompenyInfo } from '@/utils/interface'
export default function(emit: any) {
    // 表单信息
    const ruleForm = reactive<CompenyInfo>({
        shopId          : sessionStorage.getItem('shopId') as string, // 门店号
        accounttype     : 0,  // 账户类型
        accountname     : sessionStorage.getItem('merchantName') as string, // 企业名称
        createBy        : "ody", // 创建人
        mobilephone     : "", // 手机号
        customercerttype: 1,  // 客户证件类型 （对私个人证件，对公法人证件）1~身份证2-中国护照3-港澳通行证4-台湾往来大陆通行证5-临时身份证6-外国 护照7-港澳台居民居住证 对接银行为众邦银行对私只支持1-身份证
        corpcerttype    : 2,  // 企业证件类型（1-营业执照，2-组织机构代码证，3-税务登记证，4-
        idcardno        : "", // 身份证号
        date1           : new Date(),  // 客户证件有效期
        date2           : new Date(),  // 客户证件有效期
        date3           : new Date(),  // 客户证件有效期
        date4           : new Date(),  // 客户证件有效期
        address         : "", // 地址 公户营业地址 个人身份证地址
        businesslicenseno:"",// 营业执照号
        datesource      : 2,  // 来源 1:boss 2:电商 3:其他
        isSecondaryAccount: 0,  // 是否二开 1:是 0:否
        legalperson     : "", // 法人代表
        bank            : "", // 开户支行名称
        bankaccount     : "", // 银行卡号
        bankcode        : "", // 开户行号
        emailaddress    : "", // 邮箱地址
    })
    // 定义表单验证规则
    const rules = reactive<FormRules<CompenyInfo>>({
        createBy: [
            { required: true, message: '请填写创建人姓名', trigger: 'blur' },
        ],
        mobilephone: [
            { type: 'string',required: true, message: '请填写手机号码', trigger: 'blur' },
            { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
        ],
        idcardno: [
            { type: 'string',required: true, message: '请填写法人身份证号', trigger: 'blur' },
        ],
        date1: [
            { type: 'date',required: true, message: '请填写身份证有效日期', trigger: ['blur', 'change'], },
        ],
        date2: [
            { type: 'date',required: true, message: '请填写身份证有效日期', trigger: ['blur', 'change'], },
        ],
        address:[
            { required: true, message: '必填项', trigger: 'blur'},
        ],
        businesslicenseno:[
            { required: true, message: '请填写营业执照号', trigger: 'blur'},
        ],
        taxregno:[
            { required: true, message: '请填写税务登记证号', trigger: 'blur'},
        ],
        legalperson: [
            { required: true, message: '请填写法人姓名', trigger: 'blur' },
        ],
        accountname: [
            { required: true, message: '请填写账户名', trigger: 'blur' },
        ],
        bankaccount: [
            { required: true, message: '请填写银行卡号', trigger: 'blur' },
        ],
        bank: [
            { required: true, message: '请输入开户银行', trigger: 'blur' },
        ],
        bankcode: [
            { required: true, message: '请输入开户行号', trigger: 'blur' },
        ],
        emailaddress: [
            { type: 'email',required: true, message: '请输入邮箱地址', trigger: 'blur' },
        ],
    })
    // 证件列表
    const customercerttypeList = [
        {id: 1,name: "身份证"},
        {id: 2,name: "中国护照"},
        {id: 3,name: "港澳通行证"},
        {id: 4,name: "台湾往来大陆通行证"},
        {id: 5,name: "临时身份证"},
        {id: 6,name: "外国护照"},
        {id: 7,name: "港澳台居民居住证"}, //  对接银行为众邦银行对私只支持
    ]
    // 企业类型
    // 1:三证合一 2:三证合一 0个体工户
    const corporatetypeList = [
        {id: 1,name: "个体工户"},
        {id: 2,name: "三证合一"},
    ]
    const shortcuts = [
        {
          text : '长期',
          value: () => {
            return new Date('9999-12-31');
          },
        },
        {
            text : '当前日期',
            value: () => {
              return new Date();
            },
        }
    ]
    const loading = ref(false)
    // 按钮加载状态
    const btnLoading = ref(false)
    const businessLicenseImageData = ref(<any>undefined) // UploadFile | File | undefined
    const identityFrontImageData = ref(<any>undefined)
    const identityBackImageData = ref(<any>undefined)
    // 设置默认图片
    const fileList1 = ref<{uid:number,name:string,url:string}[]>()
    const fileList2 = ref<{uid:number,name:string,url:string}[]>()
    const fileList3 = ref<{uid:number,name:string,url:string}[]>()
    let id = 0;
    let masgetId = 0;
    // 如果为编辑 则设置默认值
    if(sessionStorage.getItem('createType') == 'update'){
        loading.value = true
        yztGetUserDetail(sessionStorage.getItem('shopId') as string).then(res=>{
            if(res.data.code == 200){
                console.log('设置默认值.')
                id = res.data.data['id']
                masgetId = res.data.data['masgetId']
                ruleForm.accountname = res.data.data['accountname']
                ruleForm.createBy = res.data.data['createBy']
                ruleForm.mobilephone = res.data.data['mobilephone']
                ruleForm.customercerttype = res.data.data['customercerttype']
                ruleForm.corpcerttype = res.data.data['corpcerttype']
                ruleForm.idcardno = res.data.data['idcardno']
                ruleForm.address = res.data.data['address']
                ruleForm.businesslicenseno = res.data.data['businesslicenseno']
                // ruleForm.datesource = res.data.data['datesource']
                ruleForm.isSecondaryAccount = res.data.data['isSecondaryAccount']
                ruleForm.legalperson = res.data.data['legalperson']
                ruleForm.bank = res.data.data['bank']
                ruleForm.bankaccount = res.data.data['bankaccount']
                ruleForm.bankcode = res.data.data['bankcode']
                ruleForm.emailaddress = res.data.data['emailaddress']
                ruleForm.date1 = new Date(res.data.data['corpratecertexpiry'])
                ruleForm.date2 = new Date(res.data.data['corpratecertexpiryend'])
                ruleForm.date3 = new Date(res.data.data['customercertexpiry'])
                ruleForm.date4 = new Date(res.data.data['customercertexpiryend'])

                fileList1.value =  [
                    {
                        name : 'default-image.jpg',
                        url  : `data:image/jpeg;base64,${res.data.data['businessimage']}`,
                        uid  : -1 
                    }
                ]
                fileList2.value =  [
                    {
                        name : 'default-image.jpg',
                        url  : `data:image/jpeg;base64,${res.data.data['cardimage1']}`,
                        uid  : -1
                    }
                ]
                fileList3.value =  [
                    {
                        name : 'default-image.jpg',
                        url  : `data:image/jpeg;base64,${res.data.data['cardimage2']}`,
                        uid  : -1
                    }
                ]
                let file1 = base64ToFile(fileList1.value[0].url,fileList1.value[0].name)
                let file2 = base64ToFile(fileList2.value[0].url,fileList2.value[0].name)
                let file3 = base64ToFile(fileList3.value[0].url,fileList3.value[0].name)
                
                businessLicenseImageData.value = file1
                identityFrontImageData.value = file2
                identityBackImageData.value = file3
            }else{
                ElMessage({
                    message:res.data.message,
                    type:'error'
                })
            }
            loading.value = false
        }).catch(err=>{
            ElMessage({
                message:err,
                type:'error'
            })
            loading.value = false
        })
    }
    // 修改日期
    function changeDate(date: string | Date) {
        console.log("修改日期:",date);
    }
    // 提交表单
    const submitForm = async (formEl: FormInstance | undefined) => {
        btnLoading.value = true
        console.log('submit!',toRaw(ruleForm))
        if (!formEl) return
        let tishi = ""
        if(!(identityBackImageData.value && identityBackImageData.value instanceof File)){
            tishi = '请上传身份证国徽面照片'
        }
        if(!(identityFrontImageData.value && identityFrontImageData.value instanceof File)){
            tishi = '请上传身份证公民信息面照片'
        }
        if(!(businessLicenseImageData.value && businessLicenseImageData.value instanceof File)){
            tishi = '请上传营业执照照片'
        }
        if(tishi != ""){
            ElMessage({
                message:tishi,
                type:"error"
            })
            btnLoading.value = false
            return false;
        }
        await formEl.validate((valid, fields) => {
            if (valid) {
                console.log('submit!',ruleForm)
                let formDatas = new FormData()
                if(sessionStorage.getItem('createType') == 'update'){
                    formDatas.append('id',id.toString())
                    formDatas.append('masgetId',masgetId.toString())
                }
                   
                for(let key in ruleForm){
                    // 过滤字段
                    if(!['data1','data2','data3','data4'].includes(key)){
                        formDatas.append(key,(ruleForm as any)[key])
                    }
                }
                let date1 = new Date(ruleForm.date1)
                formDatas.append('corpratecertexpiry',`${date1.getFullYear()}-${date1.getMonth()+1}-${date1.getDate()}`)
                let date2 = new Date(ruleForm.date2)
                formDatas.append('corpratecertexpiryend',`${date2.getFullYear()}-${date2.getMonth()+1}-${date2.getDate()}`)
                let date3 = new Date(ruleForm.date3)
                formDatas.append('customercertexpiry',`${date3.getFullYear()}-${date3.getMonth()+1}-${date3.getDate()}`)
                let date4 = new Date(ruleForm.date4)
                formDatas.append('customercertexpiryend',`${date4.getFullYear()}-${date4.getMonth()+1}-${date4.getDate()}`)
                formDatas.append('businessLicenseImage',businessLicenseImageData.value as any)
                formDatas.append('identityFrontImage',identityFrontImageData.value as any)
                formDatas.append('identityBackImage',identityBackImageData.value as any)
               
                console.log('请求接口数据:',formDatas);
                addUser(formDatas).then(res=>{
                    console.log('请求接口数据:',res);
                    if(res.data.code == 200){
                        ElMessage({
                            message : res.data.msg,
                            type    : "success",
                            duration: 2 * 1000
                        });
                        emit('update-data', 1);
                    }else{
                        ElMessage({
                            message : res.data.msg,
                            type    : "error",
                            duration: 2 * 1000
                        });
                    }
                    btnLoading.value = false
                }).catch(err=>{
                    ElMessage({
                        message : err,
                        type    : "error",
                        duration: 2 * 1000
                    });
                    btnLoading.value = false
                })
            } else {
                ElMessage({
                    message : "请检查表单填写内容",
                    type    : "error",
                    duration: 2 * 1000
                    });
                console.log('error submit!', fields)
                btnLoading.value = false
            }
        })
    }
    // 取消表单
    const resetForm = (formEl: FormInstance | undefined) => {
        fileList1.value =  []
        fileList2.value =  []
        fileList3.value =  []
        businessLicenseImageData.value = undefined
        identityFrontImageData.value = undefined
        identityBackImageData.value = undefined
        ruleForm.date1 = new Date()
        ruleForm.date2 = new Date()
        if (!formEl) return
        formEl.resetFields()
    }
    // 营业执照
    const businessLicenseImage = ref();
    const handleRemove1 = () => {
        console.log('删除营业执照')
        businessLicenseImage.value.clearFiles();
        businessLicenseImageData.value = undefined
    }
    const handleChange1 = (file:UploadFile) => {
        console.log('更新营业执照:',file);
        if ((file.size as number) / 1024 / 1024 > 4) {
            ElMessage.error('图片大小不要超过4M!')
            handleRemove1()
            return false
        }
        businessLicenseImageData.value = file.raw;
    };
    // 身份证正面
    const identityFrontImage = ref();
    const handleRemove2 = () => {
        identityFrontImage.value.clearFiles();
        identityFrontImageData.value = undefined
    }
    const handleChange2 = (file:UploadFile) => {
        console.log('更新身份证信息面:',file);
        if ((file.size as number) / 1024 / 1024 > 4) {
            ElMessage.error('图片大小不要超过4M!')
            handleRemove2()
            return false
        }
        identityFrontImageData.value = file.raw;
    };
    // 身份证国徽面
    const identityBackImage = ref();
    const handleRemove3 = () => {
        identityBackImage.value.clearFiles();
        identityBackImageData.value = undefined
    }
    const handleChange3 = (file:UploadFile) => {
        console.log('更新身份证国徽面:',file);
        if ((file.size as number) / 1024 / 1024 > 4) {
            ElMessage.error('图片大小不要超过4M!')
            handleRemove3()
            return false
        }
        identityBackImageData.value = file.raw;
    };
    return {
        submitForm,
        resetForm,
        btnLoading,
        ruleForm,
        rules,
        changeDate,
        customercerttypeList,
        corporatetypeList,
        shortcuts,
        handleRemove1, 
        handleChange1,
        handleRemove2, 
        handleChange2,
        handleRemove3, 
        handleChange3,
        businessLicenseImage,
        identityFrontImage,
        identityBackImage,
        fileList1,
        fileList2,
        fileList3,
        loading,
    }
}